package cpu.footprint.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.LocalStorage;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.MD5Util;

/**
 * Created by Administrator on 2017/3/7.
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
    @ViewInject(R.id.edit_userName)
    private EditText edit_userName;
    @ViewInject(R.id.edit_password)
    private EditText edit_password;
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    private AppXUtilDao mAppXUtilDao;//访问网络Dao层工具类
    private String mModilePhone;//电话号码
    private String mPassword;//密码
    private Dialog mDialog;
    private Intent intent = null;
    private User user = new User();
    private MyApplication myApplication;
    private boolean IMLoginFinsh = false;//Im登录是否成功
    private boolean LocalLoginFinsh = false;//本地登录是否成功
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ResultMessage.IMLOGIN_SUCCESS: {
                    myApplication.setIsLogin(true);
                    IMLoginFinsh = true;
                    GetLogin();
                }
                break;
                case ResultMessage.IMLOGIN_FAILED: {
                    if (mDialog != null) {
                        if (mDialog.isShowing())
                            mDialog.dismiss();
                    }
                    myApplication.setIsLogin(false);
                    String message = msg.obj.toString();
                    IMLoginFinsh = false;
                    Toast.makeText(getApplicationContext(), "登录失败:" + message,
                            Toast.LENGTH_SHORT).show();
                }
                break;
                case ResultMessage.FAILED:
                    if (mDialog != null) {
                        if (mDialog.isShowing())
                            mDialog.dismiss();
                    }
                    myApplication.setIsLogin(false);
                    Toast.makeText(LoginActivity.this, "连接失败", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case ResultMessage.TIMEOUT:
                    if (mDialog != null) {
                        if (mDialog.isShowing())
                            mDialog.dismiss();
                    }
                    myApplication.setIsLogin(false);
                    Toast.makeText(LoginActivity.this, "连接超时", Toast.LENGTH_SHORT)
                            .show();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 开始登录跳转
     */
    private void GetLogin() {
        if (IMLoginFinsh && LocalLoginFinsh) {
            mDialog.dismiss();
            CreateDialogUtil.ToastShow(LoginActivity.this, "登录成功");
            intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(0,R.anim.fade);
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        mAppXUtilDao = new AppXUtilDao();
        myApplication = (MyApplication) getApplication();
        initView();
        if (myApplication.isLogin()) {
            intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            overridePendingTransition(0,R.anim.fade);
            finish();
        } else {
            doGetLocalStorage();
        }
    }

    private void initView() {
        title_content.setText("登录");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog = showLoadingDialog(this);
        edit_userName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                edit_password.setText(null);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Event(value = {R.id.btn_login, R.id.textView_regist, R.id.textView_forgetpsw, R.id.title_back})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login: {
                mModilePhone = edit_userName.getText().toString().trim();
                mPassword = edit_password.getText().toString().trim();
                mPassword = MD5Util.MD5(mPassword);
                if (!mModilePhone.isEmpty() && !mPassword.isEmpty()) {
                    IMLogin(mModilePhone, mPassword);
                    serverLogin(mModilePhone, mPassword);
                    mDialog.show();
                } else {
                    Toast("账户和密码都不能为空!");
                }
            }
            break;
            case R.id.textView_regist: {
                Toast("注册!");
                Intent intent = new Intent(this, RegistActivity.class);
                startActivity(intent);
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            case R.id.title_back: {
                LoginActivity.this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
        }
    }

    private void serverLogin(String mobilePhone, String password) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("mobilePhone", mobilePhone);
        map.put("password", password);
        APIService.Post(ApiUrl.URL_GET_LOGIN, map, new RespCallBack<BaseBean<User>>(this) {
            @Override
            public void onSuccess(BaseBean<User> result) {
                super.onSuccess(result);
                if (result.success) {
                    user = result.data;
                    if (user != null && user.getId() != 0) {
                        myApplication.setIsLogin(true);
                        myApplication.setUser(user);
                        doLogin();
                        LocalLoginFinsh = true;
                        GetLogin();
                    } else {
                        myApplication.setIsLogin(false);
                        LocalLoginFinsh = false;
                        Toast.makeText(LoginActivity.this, result.info, Toast.LENGTH_SHORT)
                                .show();
                    }
                } else {
                    myApplication.setIsLogin(false);
                    LocalLoginFinsh = false;
                    Toast.makeText(LoginActivity.this, result.info, Toast.LENGTH_SHORT)
                            .show();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });
    }

    /**
     * 缓存登录数据在本地用于进入自动登录
     */
    void doLogin() {
        LocalStorage.saveString(LoginActivity.this, "id", String.valueOf(user.getId()));
        LocalStorage.saveUserModel(LoginActivity.this, user);
    }

    /**
     * 从本地获取用户名和Token用于获取个人信息
     */
    void doGetLocalStorage() {
        String id = LocalStorage.getString(LoginActivity.this, "id").toString().trim();
        if (id != null && !id.equals("")) {
            user = LocalStorage.getUserModel(this);
            edit_userName.setText(user.getMobilePhone());
            edit_password.setText(user.getPassword());
            edit_userName.setSelection(edit_userName.getText().length());//将光标移至文字末尾
            edit_password.setSelection(edit_password.getText().length());//将光标移至文字末尾
            serverLogin(user.getMobilePhone(), user.getPassword());
            IMLogin(user.getMobilePhone(), user.getPassword());
            mDialog.show();
        }
    }

    /**
     * IM账号登录
     *
     * @param userName
     * @param password
     */
    private void IMLogin(String userName, String password) {
        try {
            EMClient.getInstance().login(userName, password, new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    IMLoginFinsh = true;
                    mHandler.sendEmptyMessage(ResultMessage.IMLOGIN_SUCCESS);
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.d("main", "登录聊天服务器失败！");
                    mHandler.obtainMessage(ResultMessage.IMLOGIN_FAILED, message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.obtainMessage(ResultMessage.FAILED);
        }
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            LoginActivity.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
}
